<template>
  <div class="change-container">
    <div class="search" v-if="showSearch">
      <SearchBar ref="searchBarRef"
        :components="projectNature !== projectNatureEnum.projectNatureHorizontal ? conditionComponents : conditionComponents2"
        :hideRightArea="false" @search="refreshTableData" />
    </div>
    <div class="list">
      <TableForm ref="tableRef" :data="dataList" :columns="columnsCom" :tableLoading="loading" :total-count="total"
        v-model:showSearch="showSearch" :showRowSelection="true" :showPagination="true" :showToolBar="true"
        @refresh="refreshTableData" :download="(params) => { exportListData(params) }"
        :right-first-btn-permission="exportBtnPermission">
        <template #status="{ record }">
          <div class="flex items-center space-x-[8px]">
            <span class="h-[6px] w-[6px] rounded-[3px]"
              :style="{ backgroundColor: changeStatusBgColorMap[record.status as keyof typeof changeStatusBgColorMap] }" />
            <span :style="{ color: changeStatusBgColorMap[record.status as keyof typeof changeStatusBgColorMap] }">{{
              record.statusName }}</span>
          </div>
        </template>
        <!-- 纵项 -->
        <template #default="{ record }" v-if="projectNature === 1">
          <el-button link type="primary" @click="handleDetail(record.id, record.projectName)"
            v-hasPermi="['project:portrait:portraitChange:view']">查看</el-button>
          <el-button v-if="record.status === 13" link type="primary" @click="handleAudit(record.id, record.projectName)"
            v-hasPermi="['project:portrait:portraitChange:alterAudit']">变更审核</el-button>
          <el-button link type="primary" @click="handleAuditRecord(record.id)"
            v-hasPermi="['project:portrait:portraitChange:auditRecord']">审核记录</el-button>
        </template>
        <!-- 校级 -->
        <template #default="{ record }" v-else-if="projectNature === 2">
          <el-button link type="primary" @click="handleDetail(record.id, record.projectName)"
            v-hasPermi="['project:school:schoolChange:view']">查看</el-button>
          <el-button v-if="record.status === 13" link type="primary" @click="handleAudit(record.id, record.projectName)"
            v-hasPermi="['project:school:schoolChange:alterAudit']">变更审核</el-button>
          <el-button link type="primary" @click="handleAuditRecord(record.id)"
            v-hasPermi="['project:school:schoolChange:auditRecord']">审核记录</el-button>
        </template>
        <!-- 横项 -->
        <template #default="{ record }" v-else-if="projectNature === 3">
          <el-button link type="primary" @click="handleDetail(record.id, record.projectName)"
            v-hasPermi="['project:horizontalManage:horizontalChange:view']">查看</el-button>
          <el-button v-if="record.status === 13" link type="primary" @click="handleAudit(record.id, record.projectName)"
            v-hasPermi="['project:horizontalManage:horizontalChange:alterAudit']">变更审核</el-button>
          <el-button link type="primary" @click="handleAuditRecord(record.id)"
            v-hasPermi="['project:horizontalManage:horizontalChange:auditRecord']">审核记录</el-button>
        </template>
      </TableForm>
      <AuditRecordDrawer v-model:visible="auditRecordVisible" :project-id="projectId" v-if="auditRecordVisible" />
    </div>
  </div>
</template>

<script setup lang="ts" name="Index">
import { exportProjectListApi, getProjectPageApi } from '@/api/project'
import { ProjectBasePageVO, PageBeanProjectBasePageVO } from '@/types/project/response';
import { dictEnum, projectNatureEnum } from '@/utils/constEnum';
import { changeStatusBgColorMap, changeTypeMap } from '@/utils/constText';
import formateDate from '@/utils/formateDate';
import AuditRecordDrawer from '@/components/AuditRecordDrawer/index.vue'
import { downloadFile } from '@/utils/download';


const { proxy } = getCurrentInstance()

const dict = proxy.useDict(
  dictEnum.department,
  dictEnum.verticalProject,
  dictEnum.horizontalProject,
  dictEnum.schoolProjectSort,
  dictEnum.projectType,
  dictEnum.projectLevel,
  dictEnum.horizontalContractType,
)

const route = useRoute()
const router = useRouter()

const projectNature = computed(() => {
  return Number(route.query.projectNature)
})

// 导出按钮权限
const exportBtnPermission = computed(() => {
  switch (projectNature.value) {
    // 1纵向
    case projectNatureEnum.projectNaturePortrait:
      return ['project:portrait:portraitChange:export']
    // 2校级
    case projectNatureEnum.projectNatureSchool:
      return ['project:school:schoolChange:export']
    // 3横向
    case projectNatureEnum.projectNatureSchool:
      return ['project:horizontalManage:horizontalChange:export']
    default:
      return
  }
})

const showSearch = ref(true)
// 请求参数
const parameters = ref({
  page: 1,
  size: 20,
  department: '',
  projectType: '',
  projectCategory: '',
  projectLevel: '',
  managerName: '',
  projectName: '',
  status: [],
  dateArray: []
})

const defaultStatus = [13, 14]

const columnsCom = computed(() => {
  return projectNature.value === projectNatureEnum.projectNatureHorizontal ? columns2.value : columns.value
})

const conditionComponents = computed(() => [
  {
    type: 1,
    key: 'projectType',
    placeholder: '项目分类',
    config: {
      options: projectNature.value === 1 ? dict[dictEnum.verticalProject] : projectNature.value === 2 ? dict[dictEnum.schoolProjectSort] : dict[dictEnum.horizontalProject]
    }
  },
  {
    type: 1,
    key: 'projectCategory',
    placeholder: '项目类别',
    config: {
      options: dict[dictEnum.projectType]
    }
  },
  {
    type: 1,
    key: 'department',
    placeholder: '所属院系（部）',
    config: {
      options: dict[dictEnum.department]
    }
  },
  {
    type: 1,
    key: 'projectLevel',
    placeholder: '项目级别',
    config: {
      options: dict[dictEnum.projectLevel]
    }
  },
  {
    type: 2,
    key: 'dateArray',
    width: '460px',
    config: {
      startPlaceholder: '开始时间',
      endPlaceholder: '结束时间',
    }
  },
  {
    type: 1,
    key: 'status',
    placeholder: '项目状态',
    config: {
      multiple: true,
      options: [
        { title: '变更待审核', value: 13 },
        { title: '项目终止', value: 14 },
      ]
    }
  },
  {
    type: 0,
    key: 'managerName',
    placeholder: '请输入负责人',
  },
  {
    type: 0,
    key: 'projectName',
    placeholder: '请输入项目名称',
  }
])
const conditionComponents2 = computed(() => [
  {
    type: 1,
    key: 'status',
    placeholder: '项目状态',
    config: {
      multiple: true,
      options: [
        { title: '变更待审核', value: 13 },
        { title: '项目终止', value: 14 },
      ]
    }
  },
  {
    type: 1,
    key: 'projectCategory',
    placeholder: '合同类别',
    config: {
      options: dict[dictEnum.horizontalContractType]
    }
  },
  {
    type: 1,
    key: 'department',
    placeholder: '所属院系（部）',
    config: {
      options: dict[dictEnum.department]
    }
  },
  {
    type: 2,
    key: 'dateArray',
    width: '460px',
    config: {
      startPlaceholder: '开始时间',
      endPlaceholder: '结束时间',
    }
  },
  {
    type: 0,
    key: 'managerName',
    placeholder: '请输入负责人',
  },
  {
    type: 0,
    key: 'projectName',
    placeholder: '请输入项目名称',
  }
])

const tableRef = ref()
const total = ref(0)
const dataList = ref<ProjectBasePageVO[]>([])

const columns = ref([
  {
    title: '序号',
    width: 48,
    dataIndex: 'index',
    formatter: (row: any, column: any, cellValue: any, index: number) => {
      return index + 1
    }
  },
  {
    title: '项目编号',
    minWidth: 60,
    dataIndex: 'projectCode',
  },
  {
    title: '项目名称',
    minWidth: 140,
    dataIndex: 'projectName',
  },
  {
    title: '负责人',
    minWidth: 50,
    dataIndex: 'managerName',
  },
  {
    title: '团队成员',
    minWidth: 80,
    dataIndex: 'teamMember',
  },
  {
    title: '项目分类',
    minWidth: 120,
    dataIndex: 'projectTypeName',
  },
  {
    title: '项目类别',
    minWidth: 50,
    dataIndex: 'projectCategoryName',
  },
  {
    title: '所属院系（部）',
    minWidth: 80,
    dataIndex: 'departmentName',
  },
  {
    title: '起止时间',
    minWidth: 80,
    dataIndex: 'approvalTime',
    formatter: (row) => `${formateDate(row.approvalTime).format('YYYY-MM-DD')}~${formateDate(row.conclusionTime).format('YYYY-MM-DD')}`
  },
  {
    title: '项目经费',
    minWidth: 60,
    dataIndex: 'projectFunding',
  },
  {
    title: '项目级别',
    minWidth: 60,
    dataIndex: 'projectLevelName',
  },
  {
    title: '项目状态',
    minWidth: 100,
    dataIndex: 'status',
    slotName: 'status'
  },
  {
    title: '变更类型',
    minWidth: 80,
    dataIndex: 'changeType',
    formatter: (row) => changeTypeMap[row.changeType as keyof typeof changeTypeMap]
  },
  {
    title: '操作',
    width: 160,
    dataIndex: 'default',
    slotName: 'default',
  }
])

const columns2 = ref([
  {
    title: '序号',
    width: 48,
    dataIndex: 'index',
    formatter: (row: any, column: any, cellValue: any, index: number) => {
      return index + 1
    }
  },
  {
    title: '合同编号',
    minWidth: 60,
    dataIndex: 'projectCode',
  },
  {
    title: '合同名称',
    minWidth: 140,
    dataIndex: 'projectName',
  },
  {
    title: '负责人',
    minWidth: 50,
    dataIndex: 'managerName',
  },
  {
    title: '团队成员',
    minWidth: 80,
    dataIndex: 'teamMember',
  },
  {
    title: '合同类别',
    minWidth: 50,
    dataIndex: 'projectCategoryName',
  },
  {
    title: '所属院系（部）',
    minWidth: 80,
    dataIndex: 'departmentName',
  },
  {
    title: '起止时间',
    minWidth: 80,
    dataIndex: 'approvalTime',
    formatter: (row) => `${formateDate(row.approvalTime).format('YYYY-MM-DD')}~${formateDate(row.conclusionTime).format('YYYY-MM-DD')}`
  },
  {
    title: '项目经费',
    minWidth: 60,
    dataIndex: 'projectFunding',
  },
  {
    title: '项目状态',
    minWidth: 100,
    dataIndex: 'status',
    slotName: 'status'
  },
  {
    title: '变更类型',
    minWidth: 80,
    dataIndex: 'changeTypeName'
  },
  {
    title: '操作',
    width: 160,
    dataIndex: 'default',
    slotName: 'default',
  }
])

const projectId = ref('')
const auditRecordVisible = ref(false)

const { run: getData, loading } = useRequest(getProjectPageApi, {
  manual: true,
  onSuccess: (res: PageBeanProjectBasePageVO) => {
    const { content, totalElements } = res || {}
    dataList.value = content || []
    total.value = totalElements || 0
  }
})

/* 导出列表数据 */
const { runAsync: exportFile } = useRequest(exportProjectListApi, {
  manual: true,
})

// 导出
const exportListData = async (params) => {
  const data = {
    idList: [...params],
    projectNature: projectNature.value,
  }
  if (!params?.length) {
    data.status = parameters.value.status?.length > 0 ? parameters.value.status : defaultStatus
  }
  const res = await exportFile({
    ...data,
    ...searchBarRef.value.params,
    status: parameters.value.status?.length > 0 ? parameters.value.status : defaultStatus,
    approvalTime: parameters.value.dateArray?.[0],
    conclusionTime: parameters.value.dateArray?.[1]
  })
  downloadFile(res)
}

const refreshTableData = (params) => {
  parameters.value = { ...parameters.value, ...params }
  getData({
    ...parameters.value,
    projectNature: projectNature.value,
    department: parameters.value.department,
    projectType: parameters.value.projectType,
    projectCategory: parameters.value.projectCategory,
    projectLevel: parameters.value.projectLevel,
    managerName: parameters.value.managerName,
    projectName: parameters.value.projectName,
    status: parameters.value.status?.length > 0 ? parameters.value.status : defaultStatus,
    approvalTime: parameters.value.dateArray?.[0],
    conclusionTime: parameters.value.dateArray?.[1]
  })
}

const handleDetail = (id: string, name: string) => {
  router.push({ path: '/project/mine/edit', query: { projectNature: projectNature.value, projectId: id, mode: 'view', projectName: name } })
}

const handleAudit = (id: string, name: string) => {
  router.push({ path: '/project/change/changeReview', query: { projectId: id, projectName: name } })
}

const handleAuditRecord = (id: string) => {
  projectId.value = id
  auditRecordVisible.value = true
}

onMounted(() => {
  tableRef.value?.refreshInitPage()
})
</script>


<style scoped lang="scss">
.change-container {
  --at-apply: flex flex-col space-y-[16px] h-full;

  .search {
    --at-apply: px-[20px] py-[16px] bg-white rounded-[4px];
  }

  .list {
    --at-apply: flex-1 px-[20px] bg-white rounded-[4px];
  }
}
</style>